package com.example.controller;

import com.example.pojo.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/7/2 9:10
 */
@RestController
@RequestMapping(value = "/test")
@Slf4j
public class TestController {

    private int GONGGONG_COUNT = 10;
    private int operator = 5;
    private Lock lock = new ReentrantLock();

    @PostMapping(value = "/testMethod", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseInfo TestMethod() {
        ResponseInfo response = new ResponseInfo();
        lock.lock();
        try {
            if (GONGGONG_COUNT > 0) {
                GONGGONG_COUNT--;
                response.setCode("0").setMsg("获取成功").setData(Thread.currentThread().getName());
                log.info("剩余访问个数 --> " + GONGGONG_COUNT);
            } else {
                response.setCode("1").setMsg("获取失败").setData("");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return response;
    }

    @PostMapping(value = "/testMethod2", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseInfo TestMehtod2() {
        ResponseInfo response = new ResponseInfo();
        lock.lock();
        try {
            if (operator > 0) {
                operator--;
                GONGGONG_COUNT++;
                response.setCode("0").setMsg("更改成功").setData(Thread.currentThread().getName());
                log.info("剩余访问个数 --> " + GONGGONG_COUNT);

            } else {
                response.setCode("1").setMsg("更改失败").setData("");
                log.info("剩余访问个数 --> " + GONGGONG_COUNT);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


        return response;
    }


}
